var tddjs = tddjs || {};

tddjs.ListController = function (listView, backend) {
    this.view = listView;
    this.backend = backend;
    
    var self = this;
    
    jQuery(this.view).bind("click", function(event) { self.markDone(event.target); });
};

tddjs.ListController.prototype = {
    init: function () {
        var self = this;
		
        this.backend.all(function (err, items) {
            if (err) {
                return self.handleError("Server failed to get todo items", err);
            }

            var todoHTML = "", doneHTML = "", className;

            for (var i = 0, l = items.length; i < l; ++i) {
                if (items[i].done) {
                    doneHTML += "<li class='done'>" + items[i].text + "</li>";
                } else {
                    todoHTML += "<li class='todo' rel='" + items[i].id + "'>" + items[i].text + "</li>";
                }
            }

            self.view.innerHTML = todoHTML + doneHTML;
        });
    },

    handleError: function (message, err) {
        var li = document.createElement("li");
        li.className = "error";
        li.innerHTML = message;
        this.view.appendChild(li);
    },
    
    markDone: function(clickedElement) {  
    	var self = this;  	
    	this.backend.completeItem(clickedElement.getAttribute('rel'), function (err, item) {
    		if (err) {
                clickedElement.className="error";
                clickedElement.innerHTML=err.message;
                return;
            }
    		clickedElement.className = "done";	
    	}
    )},
    
    taskAdded: function(taskName) {
    	
    }
};